package com.example.flowerpcback.services;

import com.example.flowerpcback.dto.Roles;
import com.example.flowerpcback.dto.RolesExample;
import com.example.flowerpcback.mapper.RolesMapper;
import com.example.flowerpcback.req.RolesReq;
import com.example.flowerpcback.resp.PageResp;
import com.example.flowerpcback.resp.RolesResp;
import com.example.flowerpcback.utils.CopyUtil;
import com.example.flowerpcback.utils.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RoleService {
    private static final Logger LOG = LoggerFactory.getLogger(RoleService.class);

    @Resource
    private RolesMapper rolesMapper;

    @Resource
    private SnowFlake snowFlake;

    public Roles save(RolesReq req){

        Roles roles = new CopyUtil().copy(req, Roles.class);
        if(req.getId() == null){
            roles.setCreateTime(new Date());
            roles.setUpdateTime(new Date());
            Long id = snowFlake.nextId();
            req.setId(id);
            rolesMapper.insert(roles);
        }else {
            roles.setUpdateTime(new Date());
            rolesMapper.updateByPrimaryKey(roles);
        }

        return roles;

    }

    public PageResp<RolesResp> list(RolesReq req) {
        RolesExample rolesExample = new RolesExample();
        RolesExample.Criteria criteria = rolesExample.createCriteria();
        if(req.getName() != null) {
            criteria.andNameLike("%" + req.getName() + "%");
        }

        PageHelper.startPage(req.getPage(),req.getSize());
        List<Roles> rolesList = rolesMapper.selectByExample(rolesExample);

        PageInfo<Roles> pageInfo = new PageInfo<>(rolesList);
        PageResp<RolesResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setPages(pageInfo.getPages());

        List<RolesResp> rolesRespList = new CopyUtil().copyList(rolesList,RolesResp.class);

        pageResp.setList(rolesRespList);
        return pageResp;
    }

    public List<RolesResp> all(RolesReq req) {
        RolesExample rolesExample = new RolesExample();
        RolesExample.Criteria criteria = rolesExample.createCriteria();
        if(req.getName() != null) {
            criteria.andNameLike("%" + req.getName() + "%");
        }

        List<Roles> rolesList = rolesMapper.selectByExample(rolesExample);


        List<RolesResp> rolesRespList = new CopyUtil().copyList(rolesList,RolesResp.class);

        return rolesRespList;
    }

    public void delete(RolesReq req){
        rolesMapper.deleteByPrimaryKey(req.getId());
    }

}
